const express = require("express");

const userRouter = express.Router();

const db = require("../config");

/* 获取所有用户 */
userRouter.get("/getAllUsers", (req, res) => {
    const sql = 'select * from db_users where state=1';
    db.query(sql, (err, result) => {
        if (err) return res.fail(err.message);
        if (result.length == 0) return res.fail(`查询失败，请重试`);
        res.send({
            status: 0,
            message: "查询成功",
            data: result
        });
    })
});
/* 更新指定用户信息 */
userRouter.post("/updateUser", (req, res) => {

    const { id, uname, upass } = req.body;

    const sql = 'update db_users set username=?,userpasswd=? where userId=?';

    db.query(sql, [uname, upass, id], (err, result) => {
        if (err) return res.fail(err.message);
        if (result.affectedRows !== 1) return res.fail(`更新失败，请重试`);
        res.send({
            status: 0,
            message: "更新成功"
        });
    })
});
/* 删除指定用户 */
userRouter.post("/deluser", (req, res) => {
    const sql = 'update db_users set state=0 where userId=?';
    db.query(sql, req.body.id, (err, result) => {
        if (err) return res.fail(err.message);
        if (result.affectedRows !== 1) return res.fail(`删除失败，请重试`);
        res.send({
            status: 0,
            message: "删除成功"
        });
    })
});
/* 添加用户 */
userRouter.post("/addUser", (req, res) => {
    const { uname, upass } = req.body;

    const sql = "insert into db_users (username,userpasswd) values (?,?)";
    db.query(sql, [uname, upass], (err, result) => {
        if (err) return res.fail(err.message);
        if (result.affectedRows !== 1) return res.fail("注册失败，请重试");
        res.send({
            status: 0,
            message: "注册成功"
        });
    })
})

module.exports = { userRouter };